package cn.java86;

import java.sql.*;
import java.util.Properties;

/**
 * @author oldliu
 * @since 1.0
 */
public class DBUtil {
//    public static final String clsName = "com.mysql.cj.jdbc.Driver";
//    public static final String url = "jdbc:mysql://localhost:3308/java86school?useUnicode=true&characterEncoding=utf8" +
//            "&useSSL=false&serverTimezone=GMT%2B8";
//    public static final String user = "root";
//    public static final String pass = "root1234";
    private static  String clsName ;
    private static  String url  ;
    private static  String user ;
    private static  String pass;
    private DBUtil() {

    }

    static {//静态代码块，只执行一次
        try {
            Properties p=new Properties();
            p.load(DBUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            clsName=p.getProperty("clsName");
            url=p.getProperty("url");
            user=p.getProperty("user");
            pass=p.getProperty("pass");

            Class.forName(clsName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection get() {
        try {
            return DriverManager.getConnection(url, user, pass);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void close(PreparedStatement ps, Connection c) {
        close(ps);
        close(c);
    }

    public static void close(ResultSet rs, PreparedStatement ps, Connection c) {
        close(rs);
        close(ps);
        close(c);
    }

    public static void close(Connection c) {
        if (c != null) {
            try {
                c.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(PreparedStatement c) {
        if (c != null) {
            try {
                c.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Statement c) {
        if (c != null) {
            try {
                c.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(ResultSet c) {
        if (c != null) {
            try {
                c.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
